﻿using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Jet.Utilities.Serialization
{
	/// <summary>
	/// Default realization of ISerializationService
	/// </summary>
	public class SerializationService : ISerializationService
	{
		/// <summary>
		/// <see cref="ISerializationService"/>
		/// </summary>
		public byte[] SerializeObject(object obj, int maxSize = 1024)
		{
			if (obj == null)
			{
				throw new ArgumentNullException("obj");
			}

			if (maxSize <= 0)
			{
				throw new ArgumentOutOfRangeException("maxSize");
			}

			var formatter = new BinaryFormatter();
			var array = new byte[maxSize];
			using (var stream = new MemoryStream(array))
			{
				formatter.Serialize(stream, obj);
			}
			return array;
		}

		/// <summary>
		/// <see cref="ISerializationService"/>
		/// </summary>
		public TObject DeserializeObject<TObject>(byte[] buffer)
		{
			if (buffer == null)
			{
				throw new ArgumentNullException("buffer");
			}

			var formatter = new BinaryFormatter();
			using (var stream = new MemoryStream(buffer))
			{
				var result = (TObject)formatter.Deserialize(stream);
				return result;
			}
		}
	}
}
